IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('MD3.RunCheckConstraints'))
BEGIN
	DROP PROCEDURE MD3.RunCheckConstraints
END
GO

CREATE Procedure MD3.RunCheckConstraints
AS
    
BEGIN

    SET NOCOUNT ON  

	/*
		Runs all Check Constraints found in MD3.CheckConstraints
		this is called from/in the CheckConstraints folder, after the MD3.CheckConstraints table is loaded

	*/

	

DECLARE 
	@TableName varchar(256)
	,@SchemaName varchar(256)
	,@ConstraintName varchar(256)
	,@CheckConstraintExpression varchar(max)
	,@ColumnName varchar(256)
	,@AllowNoCheck	bit
	,@DropConstraint varchar(256)
	
DECLARE CurIndexes CURSOR FOR 	
	--get a list of indexes
	SELECT TableName, SchemaName, ConstraintName, ConstraintExpression, ColumnName, AllowNoCheck, DropConstraint
	FROM MD3.CheckConstraints
	ORDER BY Id
OPEN CurIndexes
FETCH NEXT FROM curIndexes INTO 
	@TableName
	,@SchemaName 
	,@ConstraintName 
	,@CheckConstraintExpression 
	,@ColumnName
	,@AllowNoCheck
	,@DropConstraint 
WHILE @@FETCH_STATUS = 0
BEGIN 

	EXEC MD3.CreateCheckConstraint
		@SchemaName = @SchemaName,
		@TableName = @TableName,
		@ConstraintName  = @ConstraintName,
		@Expression   = @CheckConstraintExpression,
		@AllowNoCheck	  = @AllowNoCheck,
		@DropConstraint   = @DropConstraint;

	
	
	FETCH NEXT FROM curIndexes INTO 
		@TableName
		,@SchemaName 
		,@ConstraintName 
		,@CheckConstraintExpression 
		,@ColumnName
		,@AllowNoCheck
	,@DropConstraint 
END

CLOSE curIndexes
DEALLOCATE curIndexes



END
GO
